<?php

namespace App\Jobs;

use App\Models\Posts\WxPost;
use App\Models\User\WxUserOnline;
use App\Models\WxTask;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Utils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class pushTaskRewardTipJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $onlines = WxUserOnline::where('online', '>', now()->subMinute(3))->orderBy('online', 'desc')->get();
        if($onlines->isEmpty()){
            return;
        }
        global $__MINI_GLOBAL_TENANT_ID__;
        if($onlines){
            $push_times = 0;
            $onlines->map(function ($item) use ($__MINI_GLOBAL_TENANT_ID__, &$push_times){
                $task_reward_list = [];
                $user_id = $item->user_id;

                $tasks = DB::table('wx_tasks')->where('type', 0)->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__)
                    ->whereNotIn('id', function ($query) use ($user_id) {
                        $query->select('task_id')
                            ->from('wx_user_task')
                            ->where('user_id', $user_id)
                            ->where('created_at', '>=', date('Y-m-d 00:00:00', time()));
                    })->get();

                if($tasks->isNotEmpty()){
                    $tasks->map(function ($v) use ($user_id, &$task_reward_list){

                        $res1 = Utils::isTaskComplete($user_id, $v->id);
                        if($res1['code'] == 1){
                            $v->status = 1;
                        }else{
                            $res2 = Utils::isTaskComplete($user_id, $v->id, true);
                            if($res2['code'] == 1){
                                $v->status = 2;
                                $v->condition_tip = $res2['current'].'/'.$res2['condition'];
                            }else{
                                $v->status = 0;
                                $v->condition_tip = $res2['current'].'/'.$res2['condition'];
                            }
                        }

                        $v->reward_tip = FieldUtils::getGiftTypes()[(int)$v->reward_type] . '*' . $v->reward_num;

                        if($v->status == 2){
                            $task_reward_list[] = [
                                'id' => $v->id,
                                'name' => $v->name,
                                'tip' => $v->reward_tip,
                            ];
                        }

                    });
                }


                $tasks2 = DB::table('wx_tasks')->where('type', 1)->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__)
                    ->whereNotIn('id', function ($query) use ($user_id) {
                        $query->select('task_id')
                            ->from('wx_user_task')
                            ->where('user_id', $user_id);
                    })->get();

                if($tasks2->isNotEmpty()){
                    $tasks2->map(function ($v) use ($user_id, &$task_reward_list){

                        $res1 = Utils::isTaskComplete($user_id, $v->id);
                        if($res1['code'] == 1){
                            $v->status = 1;
                        }else{
                            $res2 = Utils::isTaskComplete($user_id, $v->id, true);
                            if($res2['code'] == 1){
                                $v->status = 2;
                                $v->condition_tip = $res2['current'].'/'.$res2['condition'];
                            }else{
                                $v->status = 0;
                                $v->condition_tip = $res2['current'].'/'.$res2['condition'];
                            }
                        }

                        $v->reward_tip = FieldUtils::getGiftTypes()[(int)$v->reward_type] . '*' . $v->reward_num;

                        if($v->status == 2){
                            $task_reward_list[] = [
                                'id' => $v->id,
                                'name' => $v->name,
                                'tip' => $v->reward_tip,
                            ];
                        }

                    });
                }

                if($task_reward_list){

                    $title = '';
                    $content = '';
                    $taskID = '';

                    foreach ($task_reward_list as $item){
                        if(!_empty_($title)){
                            $title .= ',';
                        }
                        $title .= $item['name'];

                        if(!_empty_($content)){
                            $content .= ',';
                        }
                        $content .= $item['tip'];

                        if(!_empty_($taskID)){
                            $taskID .= ',';
                        }
                        $taskID .= $item['id'];

                    }

                    if(count($task_reward_list) >= 2){
                        $title = $task_reward_list[0]['name'].'等'.count($task_reward_list).'条任务';
                    }

                    GatewayUtils::success(GatewayUtils::uid2client_id($user_id), 14, [
                        'title' => $title,
                        'content' => $content,
                        'taskID' => $taskID,
                        'icon' => 'https://img.mini.minisns.cn/hbx/taskreward.png'
                    ]);

                    $push_times += 1;
                }

            });
            _logger_(__file__, __line__, '推送了任务奖励提示'.$push_times.'次');
        }
    }
}
